package com.huterox.todoscheduler.core.suports;

import com.huterox.todoscheduler.common.BeanNameConvert;
import com.huterox.todoscheduler.common.ConfigurationParse;
import com.huterox.todoscheduler.config.ConfigEngine;
import com.huterox.todoscheduler.config.Configuration;
import com.huterox.todoscheduler.core.beans.BeanDefinition;
import java.io.File;;
import java.io.Serializable;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


/**
 * 扫描当前需要被放在容器当中的类
 * */
public class BeanDefinitionReader implements Serializable {

    private List<String> registryBeanClass = new ArrayList<>();
    
    public BeanDefinitionReader() {
        //初始化配置
        ConfigurationParse configurationParse = 
                (ConfigurationParse)ConfigEngine.corePart.get(ConfigurationParse.class);
        configurationParse.parseConfig();
        //初始化时，扫描目标包
        doScanner(Configuration.scanPackage);
        doLoadBeanDefinitions();
    }

    //负责读取配置文件
    public List<BeanDefinition> doLoadBeanDefinitions() {
        //这里注意此时我们存入的是类的包名com.xx.xx.xx
        List<BeanDefinition> result = new ArrayList<>();
        try {
            for (String className:registryBeanClass){
                Class<?> beanClass = Class.forName(className);
                if(beanClass.isInterface()) continue;
                result.add(doCreateBeanDefinition(BeanNameConvert.toLowerFirstCase(beanClass.getSimpleName()), beanClass.getName()));
                //同时把对应的接口也扫描进去
                for(Class<?> InfClass:beanClass.getInterfaces()){
                    result.add(doCreateBeanDefinition(InfClass.getSimpleName(), beanClass.getName()));
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return result;
    }

    private BeanDefinition doCreateBeanDefinition(String factoryBeanName, String beanClassName) {
        BeanDefinition beanDefinition = new BeanDefinition();
        beanDefinition.setFactoryBeanName(factoryBeanName);
        beanDefinition.setBeanClassName(beanClassName);
        return beanDefinition;
    }
    
    private void doScanner(String scanPackage){
        // 扫描我们想要控制的那个包下面的所有类
        URL url = this.getClass().getClassLoader().getResource("/" + scanPackage.replaceAll("\\.", "/"));
        assert url != null;
        File classDir = new File(url.getFile());
        for(File file: Objects.requireNonNull(classDir.listFiles())){
            if(file.isDirectory()){
                this.doScanner(scanPackage+"."+file.getName());
            }else {
                if (!file.getName().endsWith(".class")) continue;
                String clazzName = (scanPackage + "." + file.getName().replace(".class", ""));
                registryBeanClass.add(clazzName);
            }
        }
    }


}
